package com.ndp.fb.mq.service.schedulerservice.adpublish;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.NotificationMessageKey;
import com.ndp.fb.enums.publish.PublishResultType;
import com.ndp.fb.enums.publish.PublishStatus;
import com.ndp.fb.mq.api.producer.EventNotificationMessageProducerService;
import com.ndp.fb.rdb.api.PublishBatchRdbService;
import com.ndp.fb.rdb.model.PublishBatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * Created by Elvis on 2015/3/10.
 */
@Component
public class PublishAdGroupStatusScanService {

    private static Logger logger = LoggerFactory.getLogger(PublishAdGroupStatusScanService.class);

    @Autowired
    private EventNotificationMessageProducerService eventNotificationMessageProducerService;

    @Reference
    PublishBatchRdbService publishBathRdbService;

    public void execute() {
        List<PublishBatch> batchList = publishBathRdbService.findByPublishStatus(1);
        if (CollectionUtils.isNotEmpty(batchList)) {
            for (PublishBatch publishBatch : batchList) {
                Integer success = publishBathRdbService.findResultCountByBatchIdAndTypes(publishBatch.getId(), PublishResultType.adGroupSuccess.getIndex());
                Integer fail = publishBathRdbService.findResultCountByBatchIdAndTypes(publishBatch.getId(), PublishResultType.adGroupFail.getIndex());

                int successInt = success == null ? 0 : success;
                int failInt = success == null ? 0 : fail;

                if (successInt + failInt >= publishBatch.getAllAdGroupCount()) {
                    if (successInt ==publishBatch.getAllAdGroupCount()) {//如果重试后adgroup已经全部完成，则标示为成功。
                        publishBathRdbService.updatePublishStatusById(publishBatch.getId(), PublishStatus.SUCCEED.getCode());
                    } else {
                        publishBathRdbService.updatePublishFail(publishBatch.getId(), CommonConstants.PUBLISH_FAIL);
                        //推送发布失败
                        eventNotificationMessageProducerService.sendMessage(publishBatch.getUserId(), NotificationMessageKey.N_008, null,"#!adList");
                    }
                    logger.info("BatchId_" + publishBatch.getId() + "创建Adgroup完成");
                }
            }
        }
    }

}
